import path from "node:path";
import fs from "fs-extra";
import { UiScript, UiStyle, UiTemplate } from ".";
import util, { LogType, dom, log } from "../util";

export class UiFile {

    template: UiTemplate;
    script: UiScript;
    style: UiStyle;
    source: string;

    constructor(public src: string, public dest: string, public isApp?: Boolean | undefined) {
        this.source = util.readFile(src);
        let { script: { code: scriptCode }, template: { code: templateCode }, style: { code: styleCode } } = dom.getSFC(this.source);
        this.template = new UiTemplate(templateCode, isApp);
        this.script = new UiScript(scriptCode, isApp);
        this.style = new UiStyle(styleCode, isApp);
    }

    get config() {
        return this.script.config;
    }
    get pages() {
        return this.script.pages;
    }

    async writeFile(relativePath: string) {
        // try {
        let templateCode = await this.template.generator();
        let scriptCode = await this.script.generator();
        let styleCode = await this.style.generator();
        let code = dom.combineCode(templateCode, scriptCode, styleCode);
        util.writeFile(this.dest, code);
        log.msg(LogType.WRITE, `${relativePath}`);
        this.copyImages(relativePath);
        // }
        // catch (e) {
        //     log.error(`写入${relativePath}失败，${e}`);
        // }
    }

    copyImages(relativePath: string) {
        const srcDir = path.join(path.dirname(this.src), 'images');
        const destDir = path.join(path.dirname(this.dest), 'images');
        try {
            if (fs.existsSync(srcDir) && !fs.existsSync(destDir)) {
                const relativeDir = path.join(path.dirname(relativePath), 'images');
                fs.copySync(srcDir, destDir);
                log.msg(LogType.COPY, `${relativeDir}目录`);
            }
        }
        catch (e) {
            log.error(`拷贝${srcDir}失败，${e}`);
        }
    }
}
